import { NextResponse } from 'next/server';
import { SqliteDatabase } from '@/lib/sqlite-database';

export async function POST() {
  const db = new SqliteDatabase();
  try {
    // 重置设备表ID
    console.log('开始重置设备表ID...');
    await db.exec(`
      CREATE TEMPORARY TABLE temp_devices AS
      SELECT name, classification_name, classification_code, specialty,
             naming_table_id, position_table_id, base_params_table_id,
             tech_spec_table_id, sequence_number, remarks,
             created_at, updated_at
      FROM devices
      ORDER BY id;

      DELETE FROM devices;
      DELETE FROM sqlite_sequence WHERE name='devices';

      INSERT INTO devices (
        name, classification_name, classification_code, specialty,
        naming_table_id, position_table_id, base_params_table_id,
        tech_spec_table_id, sequence_number, remarks,
        created_at, updated_at
      )
      SELECT * FROM temp_devices;

      DROP TABLE temp_devices;
    `);

    const devicesCount = (await db.get('SELECT COUNT(*) as count FROM devices')).count;
    const devicesMinId = (await db.get('SELECT MIN(id) as min_id FROM devices')).min_id;
    console.log(`设备表重置完成，总计 ${devicesCount} 行`);

    // 重置基础参数表ID
    console.log('开始重置基础参数表ID...');
    await db.exec(`
      CREATE TEMPORARY TABLE temp_base_parameters AS
      SELECT device_id, parameter_name, example_description, data_type, 
             measurement_class, data_source, created_at, updated_at
      FROM base_parameters
      ORDER BY device_id, parameter_name;

      DELETE FROM base_parameters;
      DELETE FROM sqlite_sequence WHERE name='base_parameters';

      INSERT INTO base_parameters (
        device_id, parameter_name, example_description, data_type,
        measurement_class, data_source, created_at, updated_at
      )
      SELECT * FROM temp_base_parameters;

      DROP TABLE temp_base_parameters;
    `);

    const baseParamsCount = (await db.get('SELECT COUNT(*) as count FROM base_parameters')).count;
    const baseParamsMinId = (await db.get('SELECT MIN(id) as min_id FROM base_parameters')).min_id;
    console.log(`基础参数表重置完成，总计 ${baseParamsCount} 行`);

    // 重置位置参数表ID
    console.log('开始重置位置参数表ID...');
    await db.exec(`
      CREATE TEMPORARY TABLE temp_position_parameters AS
      SELECT device_id, parameter_name, parameter_value, data_type,
             example_description, measurement_class, data_source, is_required,
             created_at, updated_at
      FROM position_parameters
      ORDER BY device_id, parameter_name;

      DELETE FROM position_parameters;
      DELETE FROM sqlite_sequence WHERE name='position_parameters';

      INSERT INTO position_parameters (
        device_id, parameter_name, parameter_value, data_type,
        example_description, measurement_class, data_source, is_required,
        created_at, updated_at
      )
      SELECT * FROM temp_position_parameters;

      DROP TABLE temp_position_parameters;
    `);

    const positionParamsCount = (await db.get('SELECT COUNT(*) as count FROM position_parameters')).count;
    const positionParamsMinId = (await db.get('SELECT MIN(id) as min_id FROM position_parameters')).min_id;
    console.log(`位置参数表重置完成，总计 ${positionParamsCount} 行`);

    // 重置命名参数表ID
    console.log('开始重置命名参数表ID...');
    await db.exec(`
      CREATE TEMPORARY TABLE temp_naming_parameters AS
      SELECT device_id, parameter_name, parameter_value, data_type,
             example_description, measurement_class, data_source, is_required,
             created_at, updated_at
      FROM naming_parameters
      ORDER BY device_id, parameter_name;

      DELETE FROM naming_parameters;
      DELETE FROM sqlite_sequence WHERE name='naming_parameters';

      INSERT INTO naming_parameters (
        device_id, parameter_name, parameter_value, data_type,
        example_description, measurement_class, data_source, is_required,
        created_at, updated_at
      )
      SELECT * FROM temp_naming_parameters;

      DROP TABLE temp_naming_parameters;
    `);

    const namingParamsCount = (await db.get('SELECT COUNT(*) as count FROM naming_parameters')).count;
    const namingParamsMinId = (await db.get('SELECT MIN(id) as min_id FROM naming_parameters')).min_id;
    console.log(`命名参数表重置完成，总计 ${namingParamsCount} 行`);

    return NextResponse.json({
      success: true,
      stats: {
        devices: {
          count: devicesCount,
          minId: devicesMinId
        },
        baseParameters: {
          count: baseParamsCount,
          minId: baseParamsMinId
        },
        positionParameters: {
          count: positionParamsCount,
          minId: positionParamsMinId
        },
        namingParameters: {
          count: namingParamsCount,
          minId: namingParamsMinId
        }
      }
    });
  } catch (error) {
    console.error('重置ID时出错:', error);
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    );
  }
} 